package com.music.user.listen;

import com.music.common.core.constant.Constants;
import com.music.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Author 史豪通
 * Date 2024/09/24 11:52
 */
@Slf4j
@Component
public class BloomFilterPreLoadListener {
    @Resource
    UserService userService;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    // 系统一启动，即加载用户数据到布隆过滤器里面
    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        List<String> list = userService.findUserAccount();

        String script = "return tonumber(redis.call(\"bf.add\", KEYS[1], ARGV[1]))";

        list.forEach(userAccount -> {
            stringRedisTemplate.opsForValue()
                    .getOperations()
                    .execute(new DefaultRedisScript<>(script, Long.class),
                            new ArrayList<String>() {{
                                add(Constants.WHITE_USER_ACCOUNT_KEY);
                            }},
                            userAccount);
        });

        log.info("---- 布隆过滤器白名单初始化完成 ----");
    }

    // 这个方法，是容器一关闭的时候，执行
    @EventListener(ContextClosedEvent.class)
    public void onContextClosed() {
        log.info("---- 系统关闭，释放资源 ----");
    }
}
